import threading
import tushare as ts
from sqlalchemy import create_engine
import logging
import pandas as pd
from DatetimeUtils import choose_day
from PledgeStatData import deal_append as deal_append_pledge_stat
import constant

"""
根据cal_date交易日更新，
适合一些一段时间，循环单日更新的场景，比如质押
"""
# 日志
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')
# 初始化数据库连接:
engine = create_engine(
    constant.get_db_path(),
    max_overflow=0,  # 超过连接池大小外最多创建的连接数
    pool_size=5,  # 连接池大小
    pool_timeout=30,  # 连接池中没有线程最多等待时间，否则报错
    pool_recycle=-1,  # 多久之后对连接池中的连接进行回收（重置）-1不回收
)

pro = ts.pro_api(constant.get_pro_token())

'''
更新各类数据定时器
'''


def fun_timer():
    day_updates = 30  # 设定更新30天数据
    current_day = choose_day(0).strftime('%Y%m%d')
    that_day = choose_day(day_updates).strftime('%Y%m%d')
    sql = 'select t.cal_date from trade_cal t WHERE t.cal_date >= ' + that_day + ' and t.cal_date <=' + current_day
    df = pd.read_sql(sql, engine)
    if len(df) > 0:
        for i in range(0, len(df)):
            cal_date = df.loc[i].cal_date
            deal_append_pledge_stat('', cal_date, engine, pro)

    global timer
    timer = threading.Timer(86400, fun_timer)
    timer.start()


def update_test(ts_code):
    """
    单项更新，适合测试
    """
    day_updates = 180  # 设定更新180天数据
    current_day = choose_day(0).strftime('%Y%m%d')
    that_day = choose_day(day_updates).strftime('%Y%m%d')


test_flag = False
if test_flag:
    update_test('688628.SH')
else:
    timer = threading.Timer(1, fun_timer)
    timer.start()